package com.ynet.middleground.user.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ifp.util.core.Md5;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.user.bean.AddEmployeeReq;
import com.ynet.middleground.user.bean.AddOrganRoleRelationshipReq;
import com.ynet.middleground.user.bean.AddUserRoleRelationReq;
import com.ynet.middleground.user.bean.InitializeDataEnterpriseBasicReq;
import com.ynet.middleground.user.bean.InitializeDataOrganRoleRelationshipReq;
import com.ynet.middleground.user.bean.OrganizationalStructureReq;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.*;
import com.ynet.middleground.user.entity.ColdchainHistory;
import com.ynet.middleground.user.entity.EmployeeInformation;
import com.ynet.middleground.user.entity.EnterpriseBasicInfo;
import com.ynet.middleground.user.entity.EnterpriseUserInfo;
import com.ynet.middleground.user.entity.InPortRole;
import com.ynet.middleground.user.entity.InitializeUserBaseInformation;
import com.ynet.middleground.user.entity.OrganizationalRoleRelation;
import com.ynet.middleground.user.entity.OrganizationalStructure;
import com.ynet.middleground.user.entity.UserBaseInformation;
import com.ynet.middleground.user.entity.UserRoleRelation;
import com.ynet.middleground.user.utils.BeanUtil;
import com.ynet.middleground.user.utils.CommUtils;

import org.apache.commons.lang.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @program: 2019-10-12_userCenter
 * @description: 黑白名单管理事务
 * @author: DaiGaoLe
 * @create: 2019-10-30 16:54
 **/
@Component
public class InitializeDataModel {

    @Autowired
    OrganizationalRoleRelationMapper organizationalRoleRelationMapper;

    @Autowired
    OrganizationalStructureMapper organizationalStructureMapper;

    @Autowired
    UserBaseInformationMapper userBaseInformationMapper;

    @Autowired
    InPortRoleMapper inPortRoleMapper;

    @Autowired
    private CommUtilsMapper commUtilsMapper;

    @Autowired
    private Mapper dozerBeanMapper;

    @Autowired
    private EnterpriseBasicInfoMapper enterpriseBasicInfoMapper;

    @Autowired
    private EnterpriseUserInfoMapper enterpriseUserInfoMapper;

    @Autowired
    private InitializeUserBaseInformationMapper initializeUserBaseInformationMapper;

    @Autowired
    private UserRoleRelationModel userRoleRelationModel;

    /*  新增黑白名单 begin */
    @Transactional(rollbackFor = Exception.class)
    public String initializeDataOrganRoleRelationship(InitializeDataOrganRoleRelationshipReq requestObject) {
        String organRoleRelationship = requestObject.getOrganRoleRelationship();
        String type = requestObject.getType();

        String str = "[" + organRoleRelationship + "]";
        JSONArray json = JSONArray.parseArray(str);
        if (json.size() > 0) {
            for (int i = 0; i < json.size(); i++) {
                JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                String value = (String)job.get("key");
                // 1-添加员工，2-初始化机构部门角色用户关联关系,3-初始化部门
                if ("1".equals(type)) {
                    infoEmployee(value);
                } else if ("2".equals(type)) {
                    insertOrganizationalRoleRelation(value);
                } else if ("3".equals(type)) {
                    initOrganizationalStructure(value);
                }
            }
        }
        return "初始化成功";
    }

    private String insertOrganizationalRoleRelation(String value) {
        String[] strings = value.split(",");
        // 0-机构,1-部门,2-角色,3-用户姓名
        // 用户类型,0-企业用户，1-港内员工用户，2-个人用户，3-企业员工用户
        String employeeNo = strings[3];
        QueryWrapper<EmployeeInformation> queryWrapperEi = new QueryWrapper<>();
        queryWrapperEi.eq("employee_no", strings[3]);
        // 用户信息基础主表用户 状态-用户删除
        EmployeeInformation employeeInformation = employeeInformationMapper.selectOne(queryWrapperEi);
        if (employeeInformation == null) {
            throw new BusinessException("港内员工：" + employeeNo + "不存在");
        }

        String role = strings[2];
        QueryWrapper<InPortRole> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("role_name", role);
        List<InPortRole> inPortRoles = inPortRoleMapper.selectList(queryWrapper1);

        if (inPortRoles == null || inPortRoles.size() == 0) {
            throw new BusinessException("角色：" + role + "不存在");
        }

        if (inPortRoles.size() > 1) {
            throw new BusinessException("角色：" + role + "存在多条数据");
        }

        // 0-机构,1-部门,2-角色,3-用户姓名
        String organizational = strings[0];
        QueryWrapper<OrganizationalStructure> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("organizational_name", organizational);
        queryWrapper2.eq("organizational_type", "0");
        List<OrganizationalStructure> organizationals = organizationalStructureMapper.selectList(queryWrapper2);

        if (organizationals == null || organizationals.size() == 0) {
            throw new BusinessException("机构：" + organizational + "不存在");
        }

        if (organizationals.size() > 1) {
            throw new BusinessException("机构：" + organizational + "存在多条数据");
        }

        // 0-机构,1-部门,2-角色,3-用户姓名
        String department = strings[1];
        QueryWrapper<OrganizationalStructure> queryWrapper3 = new QueryWrapper<>();

        queryWrapper3.eq("parent_id", organizationals.get(0).getOrganizationalId());
        queryWrapper3.eq("organizational_name", department);
        queryWrapper3.eq("organizational_type", "1");
        List<OrganizationalStructure> departments = organizationalStructureMapper.selectList(queryWrapper3);

        if (departments == null || departments.size() == 0) {
            throw new BusinessException("部门：" + department + "不存在");
        }

        if (departments.size() > 1) {
            throw new BusinessException("部门：" + department + "存在多条数据");
        }

        QueryWrapper<OrganizationalRoleRelation> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("role_id", inPortRoles.get(0).getRoleId());
        queryWrapper4.eq("user_id", employeeInformation.getUserId());
        queryWrapper4.eq("organizational_id", departments.get(0).getOrganizationalId());
        queryWrapper4.eq("channel", "C05");

        List<OrganizationalRoleRelation> organizationalRoleRelations =
            organizationalRoleRelationMapper.selectList(queryWrapper4);
        if (organizationalRoleRelations != null && organizationalRoleRelations.size() > 0) {
            return strings[0] + strings[1] + strings[2] + strings[3] + "关联关系已经存在:" + organizationalRoleRelations.size()
                + "条";
        }

        OrganizationalRoleRelation organizationalRoleRelation = new OrganizationalRoleRelation();
        organizationalRoleRelation.setRoleId(inPortRoles.get(0).getRoleId());
        organizationalRoleRelation.setUserId(employeeInformation.getUserId());
        organizationalRoleRelation.setOrganizationalId(departments.get(0).getOrganizationalId());
        organizationalRoleRelation.setChannel("C05");
        organizationalRoleRelation.setDescribeStr("初始化数据");
        organizationalRoleRelation.setCreateBy(0);
        organizationalRoleRelation.setModifiedBy(0);
        organizationalRoleRelation.setGmtModified(LocalDateTime.now());
        organizationalRoleRelationMapper.insert(organizationalRoleRelation);
        return strings[0] + strings[1] + strings[2] + strings[3] + "初始化成功：关系id：" + organizationalRoleRelation.getId();
    }

    //

    @Autowired
    OrganizationManagementModel organizationManagementModel;

    @Autowired
    EmployeeInformationMapper employeeInformationMapper;

    public String infoEmployee(String value) {
        String[] strings = value.split(",");

        QueryWrapper<EmployeeInformation> queryWrapperEi = new QueryWrapper<>();
        queryWrapperEi.eq("employee_no", strings[0]);
        // 用户信息基础主表用户 状态-用户删除
        EmployeeInformation employeeInformation = employeeInformationMapper.selectOne(queryWrapperEi);
        if (employeeInformation != null) {
            System.out.println("员工工号：" + strings[0] + "已经存在，跳过");
            return "员工工号：" + strings[0] + "已经存在，跳过";
        }

        // 0-员工编号,1-是否有效标识,2-头像,3-用户账号,4-密码,5-手机号,6-用户姓名,7-邮件
        AddEmployeeReq addEmployeeReq = new AddEmployeeReq();
        addEmployeeReq.setEmployeeNo(strings[0]);
        if ("是".equals(strings[1])) {
            addEmployeeReq.setFlag("0");
        } else {
            addEmployeeReq.setFlag("1");
        }

        if (!"无".equals(strings[2])) {
            addEmployeeReq.setHeadPortrait(strings[2]);
        }
        addEmployeeReq.setUserAccounts(strings[3]);
        addEmployeeReq.setUserPassword(strings[4]);
        addEmployeeReq.setTelephone(strings[5]);
        addEmployeeReq.setUserName(strings[6]);
        addEmployeeReq.setEmail(strings[7]);
        addEmployeeReq.setRemark("初始化数据");
        addEmployeeReq.setChannel("C05");
        addEmployeeReq.setOperationUserId(0);
        addEmployeeReq.setRequestTime(new Date());
        addEmployeeReq.setTraceId(CommUtils.getRandomId());
        organizationManagementModel.addEmployee(addEmployeeReq);
        return "初始化成功";
    };
    //

    //

    public String initOrganizationalStructure(String value) {
        OrganizationalStructureReq requestObject = new OrganizationalStructureReq();
        String[] strings = value.split(",");
        // 0-机构名称,1-部门名称,2-部门编号,3-负责人,4-联系地址(机构必填),5-邮政编码,6-标识,7-排序字段(必填),8-电话,9-传真,10-邮箱

        // 0-机构,1-部门,2-角色,3-用户姓名
        String organizational = strings[0];
        QueryWrapper<OrganizationalStructure> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("organizational_name", organizational);
        queryWrapper2.eq("organizational_type", "0");
        List<OrganizationalStructure> organizationals = organizationalStructureMapper.selectList(queryWrapper2);

        if (organizationals == null || organizationals.size() == 0) {
            throw new BusinessException("机构：" + organizational + "不存在");
        }

        if (organizationals.size() > 1) {
            throw new BusinessException("机构：" + organizational + "存在多条数据");
        }

        requestObject.setParentId(organizationals.get(0).getOrganizationalId());
        // 类型(机构、部门)0-机构，1-部门
        requestObject.setOrganizationalType("1");
        requestObject.setOrganizationalCode(strings[2]);
        requestObject.setOrganizationalName(strings[1]);
        if (!"无".equals(strings[3])) {
            // 负责人
            requestObject.setResponsiblePerson(strings[3]);
        }
        if (!"无".equals(strings[4])) {
            // 联系地址(机构必填)
            requestObject.setContactAddress(strings[4]);
        }
        if (!"无".equals(strings[5])) {
            // 邮政编码
            requestObject.setPostalCode(strings[5]);
        }
        if ("是".equals(strings[6])) {// 0-可用，1-不可用
            requestObject.setFlag("0");
        } else {
            requestObject.setFlag("1");
        }
        if (!"无".equals(strings[7])) {
            // 排序
            requestObject.setSortNumber(Integer.valueOf(strings[7]));
        }
        if (!"无".equals(strings[8])) {
            // phone
            requestObject.setPhone(strings[8]);
        }
        if (!"无".equals(strings[9])) {
            // 传真
            requestObject.setFacsimile(strings[9]);
        }
        if (!"无".equals(strings[10])) {
            // 邮箱
            requestObject.setEmail(strings[10]);
        }
        requestObject.setRemark("初始化历史数据");
        requestObject.setTraceId(CommUtils.getRandomId());
        requestObject.setChannel("C05");
        requestObject.setOperationUserId(0);
        requestObject.setRequestTime(new Date());
        organizationManagementModel.addOrganizationalStructure(requestObject);
        return null;
    }

    //
    @Transactional(rollbackFor = Exception.class)
    public Integer testAddEmployee(AddEmployeeReq requestObject) {
        // 声明变量 begin
        Integer operationUserId = new Integer(requestObject.getOperationUserId());
        String channel = requestObject.getChannel();
        String userAccounts = requestObject.getUserAccounts();
        String userPassword = "62C8AD0A15D9D1CA38D5DEE762A16E01";
        userPassword = userPassword.toLowerCase();
        List<EmployeeInformation> employees = new ArrayList<>();
        List<UserBaseInformation> baseInformations = new ArrayList<>();
        String flag = requestObject.getFlag();
        String salt = CommUtils.getSalt();
        String telephone = requestObject.getTelephone();
        String userName = requestObject.getUserName();
        String employeeNo = requestObject.getEmployeeNo(); // 员工编号
        // UserBaseInformation operationUser = null;
        UserBaseInformation userTemp = null;
        Integer userId = 0;
        // 声明变量 end

        // Update By Liwq On 2020-11-27 Start
        // Step1:开始进行校验
        // Step1.1: 基本的校验，例如手机号格式，邮箱格式校验，操作员是否存在等
        if (!CommUtils.isPhone(telephone)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0019_MESSAGE, ErrorMessageConstant.ECUC0019_CODE);
        } ;

        if (StringUtils.isNotEmpty(requestObject.getEmail()) && !CommUtils.isEmail(requestObject.getEmail())) {
            throw new BusinessException(ErrorMessageConstant.ECUC0020_MESSAGE, ErrorMessageConstant.ECUC0020_CODE);
        } ;
        // if (StringUtils.isNotEmpty(userPassword) && !CommUtils.checkPassword(userPassword)) {
        // throw new BusinessException(ErrorMessageConstant.ECUC0021_MESSAGE, ErrorMessageConstant.ECUC0021_CODE);
        // }
        /*operationUser = this.getById(operationUserId);
        if (operationUser == null) {
            throw new BusinessException(ErrorMessageConstant.ECUC0006_MESSAGE, ErrorMessageConstant.ECUC0006_CODE);
        }*/
        // Step1.2: 检查手机号，若有重复则提示：（手机号已经存在,请更改手机号）
        LambdaQueryWrapper<EmployeeInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmployeeInformation::getChannel, channel);
        queryWrapper.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
        queryWrapper.eq(EmployeeInformation::getTelephone, telephone);
        employees = employeeInformationMapper.selectList(queryWrapper);

        if (employees.size() > 0) {
            Set employeeName = new HashSet<String>();
            for (int i = 0; i < employees.size(); i++) {
                employeeName.add(employees.get(i).getUserName());
            }
            throw new BusinessException(ErrorMessageConstant.ECUC0024_MESSAGE + ";用户ID:" + employees.get(0).getUserId()
                + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0024_CODE);
        }
        // Step1.3: 检查工号，若工号重复则提示工号已被注册(保证工号登录)
        LambdaQueryWrapper<EmployeeInformation> queryWrapperEi = new LambdaQueryWrapper<>();
        queryWrapperEi.eq(EmployeeInformation::getChannel, channel);
        queryWrapperEi.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
        queryWrapperEi.eq(EmployeeInformation::getEmployeeNo, employeeNo);
        employees = employeeInformationMapper.selectList(queryWrapperEi);
        if (employees.size() > 0) {
            Set employeeName = new HashSet<String>();
            for (int i = 0; i < employees.size(); i++) {
                employeeName.add(employees.get(i).getUserName());
            }
            throw new BusinessException(ErrorMessageConstant.ECUC0053_MESSAGE + ";用户ID:" + employees.get(0).getUserId()
                + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0053_CODE);
        }
        // Step1.4: 根据手机号能找到用户的话，本次添加的账号，要和之前添加的账号信息一样；
        baseInformations = commUtilsMapper.getEmployeesByPhone(telephone);
        if (baseInformations.size() > 0) {
            if (!userAccounts.equals(baseInformations.get(0).getUserAccounts())) {
                throw new BusinessException(ErrorMessageConstant.ECUC0057_MESSAGE + ";此手机号用户已经注册，用户账号为:"
                    + baseInformations.get(0).getUserAccounts(), ErrorMessageConstant.ECUC0057_CODE);
            }
        }

        // Step2: 校验通过，将信息保存到表里
        // Step2.1: 保存到基本信息表：ur_user_base_information
        // 根据手机号能查到的话，就代表之前这个用户在别的渠道添加过，主表已经有数据，所以只往附表添加；
        // 查不到，才往主表添加
        if (baseInformations.size() == 0) {
            // 用户以前没有添加过，往主表添加数据，要校验账号不能重复；
            LambdaQueryWrapper<UserBaseInformation> q = new LambdaQueryWrapper<>();
            q.eq(UserBaseInformation::getUserAccounts, userAccounts);
            q.eq(UserBaseInformation::getIsDelete, "0");
            List<UserBaseInformation> userList = userBaseInformationMapper.selectList(q);
            if (userList.size() > 0) {
                LambdaQueryWrapper<EmployeeInformation> qwEi = new LambdaQueryWrapper<>();
                qwEi.eq(EmployeeInformation::getChannel, channel);
                qwEi.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
                qwEi.eq(EmployeeInformation::getUserId, userList.get(0).getUserId());
                employees = employeeInformationMapper.selectList(qwEi);
                Set employeeName = new HashSet<String>();
                for (int i = 0; i < employees.size(); i++) {
                    employeeName.add(employees.get(i).getUserName());
                }
                throw new BusinessException(ErrorMessageConstant.ECUC0001_MESSAGE + ";用户ID:"
                    + userList.get(0).getUserId() + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0001_CODE);
            }
            // 用户以前没有添加过，校验员工号在所有渠道下都不能重复。
            LambdaQueryWrapper<EmployeeInformation> query = new LambdaQueryWrapper<>();
            query.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
            query.eq(EmployeeInformation::getEmployeeNo, employeeNo);
            employees = employeeInformationMapper.selectList(query);
            if (employees.size() > 0) {
                Set employeeName = new HashSet<String>();
                for (int i = 0; i < employees.size(); i++) {
                    employeeName.add(employees.get(i).getUserName());
                }
                throw new BusinessException(ErrorMessageConstant.ECUC0053_MESSAGE + ";用户ID:"
                    + employees.get(0).getUserId() + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0053_CODE);
            }
            if (StringUtils.isBlank(userPassword)) {
                throw new BusinessException("密码不可为空", ErrorMessageConstant.ECUC0007_CODE);
            }
            UserBaseInformation userBaseInformation = dozerBeanMapper.map(requestObject, UserBaseInformation.class);
            userBaseInformation.setUserPassword(Md5.getMd5String(userPassword + salt));
            userBaseInformation.setState(SystemConstant.USER_STATE_6);
            userBaseInformation.setSalt(salt);
            userBaseInformation.setUserType(SystemConstant.USER_TYPE_1);
            userBaseInformation.setCreateBy(operationUserId);
            userBaseInformation.setModifiedBy(operationUserId);
            userBaseInformation.setGmtModified(LocalDateTime.now());
            userBaseInformation.setBusinessSeqNo(requestObject.getTraceId());
            userBaseInformationMapper.insert(userBaseInformation);

            userId = userBaseInformation.getUserId();
        }
        // 数据已经存在，主表已经有数据了，只需要添加到附表就行了
        if (baseInformations.size() > 0) {
            userId = baseInformations.get(0).getUserId();

            // 用户以前添加过信息，这次添加可能是再别的渠道注册信息。要校验员工号别人是否用过。
            LambdaQueryWrapper<EmployeeInformation> query = new LambdaQueryWrapper<>();
            query.ne(EmployeeInformation::getUserId, userId);
            query.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
            query.eq(EmployeeInformation::getEmployeeNo, employeeNo);
            employees = employeeInformationMapper.selectList(query);
            if (employees.size() > 0) {
                Set employeeName = new HashSet<String>();
                for (int i = 0; i < employees.size(); i++) {
                    employeeName.add(employees.get(i).getUserName());
                }
                throw new BusinessException(ErrorMessageConstant.ECUC0053_MESSAGE + ";用户ID:"
                    + employees.get(0).getUserId() + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0053_CODE);
            }
        }
        // Step2.1: 保存到员工信息附属表：ur_employee_information
        EmployeeInformation employeeInf = dozerBeanMapper.map(requestObject, EmployeeInformation.class);
        employeeInf.setCreateBy(operationUserId);
        employeeInf.setModifiedBy(operationUserId);
        employeeInf.setGmtModified(LocalDateTime.now());
        employeeInf.setUserId(userId);

        employeeInformationMapper.insert(employeeInf);
        return employeeInf.getUserId();
        // Update By Liwq On 2020-11-27 End
    }

    // 把一个字符串中的大写转为小写，小写转换为大写：思路2
    public static String exChange2(String str) {
        for (int i = 0; i < str.length(); i++) {
            // 如果是小写
            if (str.substring(i, i + 1).equals(str.substring(i, i + 1).toLowerCase())) {
                str.substring(i, i + 1).toUpperCase();
            } else {
                str.substring(i, i + 1).toLowerCase();
            }
        }
        return str;
    }

    @Transactional(rollbackFor = Exception.class)
    public void initializeDataEnterpriseBasic(List<InitializeDataEnterpriseBasicReq> requestObject) {
        List<InitializeUserBaseInformation> userBaseInformationList =
            BeanUtil.mapList(dozerBeanMapper, requestObject, InitializeUserBaseInformation.class);
        // OrganizationalStructure organ = new OrganizationalStructure();
        // organ.setParentId(0);
        // organ.setOrganizationalType(SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_0);
        // organ.setOrganizationalCode("无");
        // organ.setOrganizationalName("山港易付临时部门");
        // organ.setContactAddress("青岛市市北区港华路七号大港综合楼20楼");
        // organ.setFlag(SystemConstant.SYSTEOM_FLAG_0);
        // organ.setSortNumber(1);
        // organ.setChannel("C03");
        // organ.setCreateBy(0);
        // organ.setGmtCreate(LocalDateTime.now());
        // organ.setModifiedBy(0);
        // organ.setGmtModified(LocalDateTime.now());
        // organizationalStructureMapper.insert(organ);
        List<EnterpriseBasicInfo> enterpriseBasicInfoList =
            BeanUtil.mapList(dozerBeanMapper, requestObject, EnterpriseBasicInfo.class);
        List<EnterpriseUserInfo> enterpriseUserInfoList =
            BeanUtil.mapList(dozerBeanMapper, requestObject, EnterpriseUserInfo.class);
        List<EmployeeInformation> enterpriseEmployeeInfoList =
            BeanUtil.mapList(dozerBeanMapper, requestObject, EmployeeInformation.class);

        for (int i = 0; i < userBaseInformationList.size(); i++) {
            LambdaQueryWrapper<EnterpriseUserInfo> querry = new LambdaQueryWrapper<EnterpriseUserInfo>();
            querry.eq(EnterpriseUserInfo::getTelephone, requestObject.get(i).getTelephone());
            querry.or().eq(EnterpriseUserInfo::getPapersNo, requestObject.get(i).getPapersNo());
            LambdaQueryWrapper<EmployeeInformation> querryEI = new LambdaQueryWrapper<EmployeeInformation>();
            querryEI.eq(EmployeeInformation::getTelephone, requestObject.get(i).getTelephone());
//            querryEI.or().eq(EmployeeInformation::getPapersNo, requestObject.get(i).getPapersNo());
            if (SystemConstant.USER_TYPE_0.equals(userBaseInformationList.get(i).getUserType())) {
                String userAccounts = null;
                String userPassword = null;
                String salt = CommUtils.getSalt();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                userAccounts = uuid.substring(0, 20);
                userPassword = uuid;
                Integer userId = requestObject.get(i).getUserId();
                userBaseInformationList.get(i).setUserId(requestObject.get(i).getUserId());
                userBaseInformationList.get(i).setUserAccounts(userAccounts);
                userBaseInformationList.get(i).setUserPassword(CommUtils.getMd5SaltPassword(userPassword, salt));
                // userBaseInformationList.get(i).setUserType(SystemConstant.USER_TYPE_0);
                // userBaseInformationList.get(i).setState(state);
                userBaseInformationList.get(i).setSalt(salt);
                userBaseInformationList.get(i).setCreateBy(0);
                userBaseInformationList.get(i).setGmtCreate(LocalDateTime.now());
                userBaseInformationList.get(i).setModifiedBy(0);
                userBaseInformationList.get(i).setGmtModified(LocalDateTime.now());
                initializeUserBaseInformationMapper.insert(userBaseInformationList.get(i));

                enterpriseBasicInfoList.get(i).setUserName(enterpriseBasicInfoList.get(i).getCompanyName());
                enterpriseBasicInfoList.get(i).setCreateBy(0);
                enterpriseBasicInfoList.get(i).setGmtCreate(LocalDateTime.now());
                enterpriseBasicInfoList.get(i).setModifiedBy(0);
                enterpriseBasicInfoList.get(i).setGmtModified(LocalDateTime.now());
                enterpriseBasicInfoMapper.insert(enterpriseBasicInfoList.get(i));
            } else if (SystemConstant.USER_TYPE_3.equals(userBaseInformationList.get(i).getUserType())) {
                if(enterpriseUserInfoMapper.selectCount(querry) == 0) {
                String userAccounts = null;
                String userPassword = null;
                String salt = CommUtils.getSalt();
                userAccounts = userBaseInformationList.get(i).getUserAccounts();
                userPassword = userBaseInformationList.get(i).getUserPassword().toLowerCase();
                userPassword = Md5.getMd5String(userPassword + salt);
                Integer userId = requestObject.get(i).getUserId();
                userBaseInformationList.get(i).setUserId(requestObject.get(i).getUserId());
                userBaseInformationList.get(i).setUserAccounts(userAccounts);
                userBaseInformationList.get(i).setUserPassword(userPassword);
                // userBaseInformationList.get(i).setUserType(SystemConstant.USER_TYPE_0);
                // userBaseInformationList.get(i).setState(state);
                userBaseInformationList.get(i).setSalt(salt);
                userBaseInformationList.get(i).setCreateBy(0);
                userBaseInformationList.get(i).setGmtCreate(LocalDateTime.now());
                userBaseInformationList.get(i).setModifiedBy(0);
                userBaseInformationList.get(i).setGmtModified(LocalDateTime.now());
                initializeUserBaseInformationMapper.insert(userBaseInformationList.get(i));
                enterpriseUserInfoList.get(i).setCreateBy(0);
                enterpriseUserInfoList.get(i).setGmtCreate(LocalDateTime.now());
                enterpriseUserInfoList.get(i).setModifiedBy(0);
                enterpriseUserInfoList.get(i).setGmtModified(LocalDateTime.now());
                enterpriseUserInfoMapper.insert(enterpriseUserInfoList.get(i));
                }
            } else if (SystemConstant.USER_TYPE_1.equals(userBaseInformationList.get(i).getUserType())) {
                if(employeeInformationMapper.selectCount(querryEI) == 0) {
                String userAccounts = null;
                String userPassword = null;
                String salt = CommUtils.getSalt();

                userAccounts = userBaseInformationList.get(i).getUserAccounts();
                userPassword = userBaseInformationList.get(i).getUserPassword().toLowerCase();
                userPassword = Md5.getMd5String(userPassword + salt);
                Integer userId = requestObject.get(i).getUserId();
                userBaseInformationList.get(i).setUserId(requestObject.get(i).getUserId());
                userBaseInformationList.get(i).setUserAccounts(userAccounts);
                userBaseInformationList.get(i).setUserPassword(userPassword);
                userBaseInformationList.get(i).setSalt(salt);
                userBaseInformationList.get(i).setCreateBy(0);
                userBaseInformationList.get(i).setGmtCreate(LocalDateTime.now());
                userBaseInformationList.get(i).setModifiedBy(0);
                userBaseInformationList.get(i).setGmtModified(LocalDateTime.now());
                initializeUserBaseInformationMapper.insert(userBaseInformationList.get(i));
                enterpriseEmployeeInfoList.get(i).setCreateBy(0);
                enterpriseEmployeeInfoList.get(i).setGmtCreate(LocalDateTime.now());
                enterpriseEmployeeInfoList.get(i).setModifiedBy(0);
                enterpriseEmployeeInfoList.get(i).setGmtModified(LocalDateTime.now());
                employeeInformationMapper.insert(enterpriseEmployeeInfoList.get(i));
                }
            }
        }
        // for(int j=0;j<enterpriseBasicInfoList.size();j++) {
        // if(SystemConstant.USER_TYPE_0.equals(requestObject.get(j).getUserType())) {
        // enterpriseBasicInfoList.get(j).setUserName(enterpriseBasicInfoList.get(j).getCompanyName());
        // enterpriseBasicInfoList.get(j).setCreateBy(0);
        // enterpriseBasicInfoList.get(j).setGmtCreate(LocalDateTime.now());
        // enterpriseBasicInfoList.get(j).setModifiedBy(0);
        // enterpriseBasicInfoList.get(j).setGmtModified(LocalDateTime.now());
        // enterpriseBasicInfoMapper.insert(enterpriseBasicInfoList.get(j));
        // }
        // }
        // for(int k=0;k<enterpriseEmployeeInfoList.size();k++) {
        // if(SystemConstant.USER_TYPE_1.equals(requestObject.get(k).getUserType())) {
        // enterpriseEmployeeInfoList.get(k).setCreateBy(0);
        // enterpriseEmployeeInfoList.get(k).setGmtCreate(LocalDateTime.now());
        // enterpriseEmployeeInfoList.get(k).setModifiedBy(0);
        // enterpriseEmployeeInfoList.get(k).setGmtModified(LocalDateTime.now());
        // enterpriseEmployeeInfoList.get(k).setEmployeeNo(userBaseInformationList.get(k).getUserAccounts());
        //// enterpriseEmployeeInfoList.get(k).setOrganizationalId(organ.getOrganizationalId());
        // employeeInformationMapper.insert(enterpriseEmployeeInfoList.get(k));
        // }
        // }
        // for(int p=0;p<enterpriseUserInfoList.size();p++) {
        // if(SystemConstant.USER_TYPE_3.equals(requestObject.get(p).getUserType())) {
        //// LambdaQueryWrapper<UserBaseInformation> queryEBI = new LambdaQueryWrapper<UserBaseInformation>();
        //// queryEBI.eq(UserBaseInformation::getSgyfId, requestObject.get(p).getEntOperatorIds());
        //// if(userBaseInformationMapper.selectCount(queryEBI)!=0) {
        //// Integer entOperatorId = userBaseInformationMapper.selectOne(queryEBI).getUserId();
        // enterpriseUserInfoList.get(p).setEntOperatorId(0);
        // enterpriseUserInfoList.get(p).setCreateBy(0);
        // enterpriseUserInfoList.get(p).setGmtCreate(LocalDateTime.now());
        // enterpriseUserInfoList.get(p).setModifiedBy(0);
        // enterpriseUserInfoList.get(p).setGmtModified(LocalDateTime.now());
        // enterpriseUserInfoMapper.insert(enterpriseUserInfoList.get(p));
        //// }else {
        //// userBaseInformationMapper.deleteById(requestObject.get(p).getUserId());
        //// }
        // }
        // }
    }

    /**
     * @param 初始化企业员工角色关系
     */
    public void initializeEnterpriseUserRoleRelation(List<AddUserRoleRelationReq> requestObject) {
        List<UserRoleRelation> roleRelations = BeanUtil.mapList(dozerBeanMapper, requestObject, UserRoleRelation.class);
        for (int i = 0; i < roleRelations.size(); i++) {
            LambdaQueryWrapper<EnterpriseUserInfo> queryEUI = new LambdaQueryWrapper<EnterpriseUserInfo>();
            queryEUI.eq(EnterpriseUserInfo::getUserId, roleRelations.get(i).getUserId());
//            roleRelations.get(i).setChannel("C03");
            roleRelations.get(i).setCreateBy(0);
            roleRelations.get(i).setGmtCreate(LocalDateTime.now());
            roleRelations.get(i).setModifiedBy(0);
            roleRelations.get(i).setGmtModified(LocalDateTime.now());
            if (enterpriseUserInfoMapper.selectCount(queryEUI) > 0) {
                EnterpriseUserInfo temp = new EnterpriseUserInfo();
                temp = enterpriseUserInfoMapper.selectList(queryEUI).get(0);
                EnterpriseUserInfo enterpriseUserInfo = temp;
                enterpriseUserInfo.setGmtCreate(LocalDateTime.now());
                enterpriseUserInfo.setGmtModified(LocalDateTime.now());
                enterpriseUserInfo.setChannel(roleRelations.get(i).getChannel());
                enterpriseUserInfo.setEntOperatorId(roleRelations.get(i).getEnterpriseId());
                LambdaQueryWrapper<EnterpriseUserInfo> queryEUI2 = new LambdaQueryWrapper<EnterpriseUserInfo>();
                queryEUI2.eq(EnterpriseUserInfo::getUserId, roleRelations.get(i).getUserId());
                queryEUI2.eq(EnterpriseUserInfo::getEntOperatorId, roleRelations.get(i).getEnterpriseId());
                queryEUI2.eq(EnterpriseUserInfo::getChannel, roleRelations.get(i).getChannel());
                if (enterpriseUserInfoMapper.selectCount(queryEUI2) > 0) {
                } else {
                    enterpriseUserInfoMapper.insert(enterpriseUserInfo);
                }
                userRoleRelationModel.save(roleRelations.get(i));
            }
        }
        // LambdaQueryWrapper<EnterpriseUserInfo> queryEUI = new LambdaQueryWrapper<EnterpriseUserInfo>();
        // queryEUI.eq(EnterpriseUserInfo::getEntOperatorId, 0);
        // enterpriseUserInfoMapper.delete(queryEUI);
        // userRoleRelationModel.saveBatch(roleRelations);
    }

    /**
     * 数据迁移港内员工角色关系
     */
    public void initializeEmployeeRolerelation(List<AddOrganRoleRelationshipReq> requestObject) {
        List<OrganizationalRoleRelation> roleRelations =
            BeanUtil.mapList(dozerBeanMapper, requestObject, OrganizationalRoleRelation.class);
        for (int i = 0; i < roleRelations.size(); i++) {
            LambdaQueryWrapper<EmployeeInformation> queryEUI = new LambdaQueryWrapper<EmployeeInformation>();
            queryEUI.eq(EmployeeInformation::getUserId, roleRelations.get(i).getUserId());
            if (employeeInformationMapper.selectCount(queryEUI) > 0) {
                EmployeeInformation temp = new EmployeeInformation();
                temp = employeeInformationMapper.selectList(queryEUI).get(0);
                EmployeeInformation employeeInformation = temp;
                employeeInformation.setGmtCreate(LocalDateTime.now());
                employeeInformation.setCreateBy(0);
                employeeInformation.setGmtModified(LocalDateTime.now());
                employeeInformation.setModifiedBy(0);
                employeeInformation.setChannel(roleRelations.get(i).getChannel());
                employeeInformation.setOrganizationalId(roleRelations.get(i).getOrganizationalId());
                LambdaQueryWrapper<EmployeeInformation> queryEI = new LambdaQueryWrapper<EmployeeInformation>();
                queryEI.eq(EmployeeInformation::getUserId, roleRelations.get(i).getUserId());
                queryEI.eq(EmployeeInformation::getOrganizationalId, roleRelations.get(i).getOrganizationalId());
                queryEI.eq(EmployeeInformation::getChannel, roleRelations.get(i).getChannel());
                if (employeeInformationMapper.selectCount(queryEI) > 0) {
                } else {
                    employeeInformationMapper.insert(employeeInformation);
                }
                roleRelations.get(i).setCreateBy(0);
                roleRelations.get(i).setGmtCreate(LocalDateTime.now());
                roleRelations.get(i).setModifiedBy(0);
                roleRelations.get(i).setGmtModified(LocalDateTime.now());
                organizationalRoleRelationMapper.insert(roleRelations.get(i));
            }
        }
        // LambdaQueryWrapper<EmployeeInformation> queryEI = new LambdaQueryWrapper<EmployeeInformation>();
        // queryEI.eq(EmployeeInformation::getOrganizationalId, 0);
        // employeeInformationMapper.delete(queryEI);
    }
}
